<template>
  <div class="accountlogin">
    <van-nav-bar title="密码登录" fixed left-arrow @click-left="$router.back()" />

    <van-field v-model="phone" center clearable type="number" label="手机号" left-icon="phone-o" placeholder="请输入手机号" required maxlength="11" />
    <van-field v-model="password" type="password" label="密码" left-icon="eye-o" placeholder="密码8-16位" />

    <!-- 提交按钮 -->
    <div class="btn">
      <van-button type="primary" size="large" class="btn1" @click="login">登录</van-button>
    </div>
    <div class="btn">
      <van-button type="primary" size="large" class="btn2" @click="$router.push('/register')">注册</van-button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      phone: '',
      password: ''
    }
  },
  methods: {
    login() {
      if (!this.phone) return alert('电话号码不能为空！')
      if (!this.password) return alert('密码不能为空！')
      //验证手机号格式
      if (this.phone.length !== 11 || !/^1[3-9]\d{9}$/.test(this.phone)) return alert('手机号格式不正确！')
      if (this.password.length > 16 || this.password.length < 6) return alert('密码长度不正确！')
      // 密码为6-16位的数字字母组合
      if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/.test(this.password)) return alert('密码必须为数字和字母的组合！')
      const users = JSON.parse(localStorage.getItem('users')) || []
      // 验证手机号是否已经注册
      if (users.filter((user) => user.phone == this.phone).length == 0) return alert('账号还未注册！')
      //验证密码是否正确
      if (users.filter((user) => user.phone == this.phone)[0].password !== this.password) return alert('密码输入错误！')
      localStorage.setItem('curUser', this.phone)
      this.$router.replace('/more')
    }
  }
}
</script>

<style lang="less" scoped>
.accountlogin {
  padding-top: 46px;
  /deep/.van-nav-bar {
    background-color: #fff;
    margin-bottom: 5px;
  }

  /deep/.van-icon {
    color: #323232;
  }

  .btn1 {
    background-color: #ffdd74;
    border: 1px solid #ffdd74;
    border-radius: 15px;
  }
  .btn2 {
    background-color: #dddddd;
    border: 1px solid #dddddd;
    border-radius: 15px;
  }
  .btn {
    margin-top: 15px;
    padding: 0 15px;
  }
}
</style>
